import Vue from 'vue'
import Vuex from 'vuex'
import _ from 'lodash'

Vue.use(Vuex)
import {
  local
} from '../utils/cache'

import { UserService, RoleService } from '../api';
export default new Vuex.Store({
  state: {
    isShowLoading: false,
    message: '111',
    userInfo: {},
    search_id : '',
    roles: [],

   
    
  },
  mutations: {
    SHOW_LOADING(state) {
      state.isShowLoading = true
    },
    HIDE_LOADING(state) {
      state.isShowLoading = false;
    },
    
    SET_USERINFO(state, value) {
      state.userInfo = value;
      local.setJSON('userInfo',value)
    },
    
    SET_ROLES(state, value) {
      state.roles = value;
      local.setJSON('roles',value)
    },
    MESSAGE(state, value) {
      state.message = value;
    },
    SET_SEARCH(state, value) {
      state.search_id = value;
    },
    NO_MESSAGE(state) {
      state.message = '';
    },
    

  },
  actions: {
    async toLogin({
      commit
    }, info) {


      const response = await UserService.login(info);

      if (response.code == 10000) {
        local.set('token', response.data.token);
        // 设置个人信息
        const db_info = await UserService.getInfo();
        commit("SET_USERINFO", db_info.data);

        // 设置角色列表
        const sources = await RoleService.getList()
        const roles = sources.data.map(item => {
          return item.identify; 
        })
        commit("SET_ROLES", roles);
        return Promise.resolve(response.message)
      } else {
        return Promise.reject(response.message)
      }
    },
    async validatorLogin() {
      const response = await UserService.is_login();
      return response.code === 10000;
    }


  },
  getters: {
    roles: state => _.isEmpty(state.roles) ? local.getJSON('roles') : state.roles,
    userInfo: state => _.isEmpty(state.userInfo) ? local.getJSON('userInfo') : state.userInfo,
    
  },
  modules: {}
})